package com.xindaoapp.happypet.activity;

import java.util.LinkedList;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.Brand;
import com.xindaoapp.happypet.bean.ShopBrand;
import com.xindaoapp.happypet.ui.BaseActivity;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshListView;

/**
 * 品牌官
 * 
 * @author Yangqing
 * 
 */
@SuppressWarnings("unused")
public class BrandActivity extends BaseActivity implements OnClickListener {
    @ViewInject(R.id.tittle_shop_cancel)
    private ImageView tittle_shop_cancel;
    @ViewInject(R.id.tittle_shop_content)
    private TextView tittle_shop_content;

    @ViewInject(R.id.brand_list)
    private PullToRefreshListView brand_list;
    @ViewInject(R.id.loading)
    private FrameLayout loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        initClick();
        initGridView();
        initListView();
        fillDataBottom(page);
    }

    private void initListView() {
        brand_list.setPullRefreshEnabled(false);
        brand_list.setScrollLoadEnabled(false);
        brand_list.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (brandsbottom.size() > 0) {
                    brandsbottom.clear();
                }
                page = 1;
                isFirst = 1;
                fillDataBottom(page);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (count == brandsbottom.size()) {
                    onLoaded();
                    Toast.makeText(getApplicationContext(), "没有更多数据了", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    page++;
                    fillDataBottom(page);
                }
            }
        });
        brand_list.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    return;
                } else {
                    Intent intent = new Intent(BrandActivity.this, BrandListItem.class);
                    intent.putExtra("brandID", brandsbottom.get(position - 1).getBrand_id());
                    intent.putExtra("brandName", brandsbottom.get(position - 1).getBrand_name());
                    startActivity(intent);
                }
            }
        });
        setLastUpdateTime();
    }

    private class BrandBottomAdapter extends BaseAdapter {
        private final LinkedList<Brand> bottom;

        public BrandBottomAdapter(LinkedList<Brand> bottom) {
            super();
            this.bottom = bottom;
        }

        @Override
        public int getCount() {
            return bottom.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // Brand info;
            // if(position==0){
            // LinearLayout ll=(LinearLayout) View.inflate(getApplicationContext(),
            // R.layout.brand_top_gv, null);
            // GridView gv=(GridView) ll.findViewById(R.id.brand_top);
            // if(topAdapter==null){
            // topAdapter=new BrandTopAdapter(brandstop);
            // gv.setAdapter(topAdapter);
            // }else{
            // topAdapter.notifyDataSetChanged();
            // }
            // gv.setOnItemClickListener(new OnItemClickListener() {
            // @Override
            // public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // Intent intent = new Intent(BrandActivity.this, BrandListItem.class);
            // intent.putExtra("brandID", brandstop.get(position).getBrand_id());
            // intent.putExtra("brandName", brandstop.get(position).getBrand_name());
            // startActivity(intent);
            // }
            // });
            // return ll;
            // }else{
            // info=bottom.get(position);
            // }
            View view;
            ViewBottomHolder holder;

            if (convertView != null && convertView instanceof RelativeLayout) {
                view = convertView;
                holder = (ViewBottomHolder) convertView.getTag();
            } else {
                view = View.inflate(getApplicationContext(), R.layout.brand_bottom, null);
                holder = new ViewBottomHolder();
                holder.iv = (ImageView) view.findViewById(R.id.brand_iv);
                view.setTag(holder);
            }

            ImageLoader.getInstance().displayImage(bottom.get(position).getBrand_logo(), holder.iv);

            return view;

        }

    }

    class ViewBottomHolder {
        ImageView iv;
    }

    private int page = 1;

    private void initGridView() {
        fillDataTop("1", 3);
    }

    private LinkedList<Brand> brandstop;

    private BrandTopAdapter topAdapter;

    private void fillDataTop(String page, int pageSize) {
        RequestParams params = new RequestParams();
        params.put("page", "1");
        params.put("pageSize", "10");
        AddClient.get(Address.SHOPBRAND, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                try {
                    ShopBrand shop = JSON.parseObject(content, ShopBrand.class);
                    if (shop.getStatus().equals("1")) {
                        if (!shop.getMsg().equals("暂无数据！")) {
                            brandstop = shop.getData().getInfo();
                            brand_list.setPullRefreshEnabled(true);
                            brand_list.setScrollLoadEnabled(true);
                            LinearLayout ll =
                                    (LinearLayout) getLayoutInflater().inflate(
                                            R.layout.brand_top_i, null);
                            ImageView iv1 = (ImageView) ll.findViewById(R.id.iv1);
                            ImageView iv2 = (ImageView) ll.findViewById(R.id.iv2);
                            ImageView iv3 = (ImageView) ll.findViewById(R.id.iv3);


                            ImageLoader.getInstance().displayImage(
                                    brandstop.get(0).getBrand_logo(), iv1);
                            ImageLoader.getInstance().displayImage(
                                    brandstop.get(1).getBrand_logo(), iv2);
                            ImageLoader.getInstance().displayImage(
                                    brandstop.get(2).getBrand_logo(), iv3);

                            iv1.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent =
                                            new Intent(BrandActivity.this, BrandListItem.class);
                                    intent.putExtra("brandID", brandstop.get(0).getBrand_id());
                                    intent.putExtra("brandName", brandstop.get(0).getBrand_name());
                                    startActivity(intent);
                                }
                            });
                            iv2.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent =
                                            new Intent(BrandActivity.this, BrandListItem.class);
                                    intent.putExtra("brandID", brandstop.get(1).getBrand_id());
                                    intent.putExtra("brandName", brandstop.get(1).getBrand_name());
                                    startActivity(intent);
                                }
                            });
                            iv3.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent =
                                            new Intent(BrandActivity.this, BrandListItem.class);
                                    intent.putExtra("brandID", brandstop.get(2).getBrand_id());
                                    intent.putExtra("brandName", brandstop.get(2).getBrand_name());
                                    startActivity(intent);
                                }
                            });
                            if (bottomAdapter == null) {
                                try {
                                    Thread.sleep(600);
                                    brand_list.getRefreshableView().addHeaderView(ll);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
            }
        });
    }

    private final LinkedList<Brand> brandsbottom = new LinkedList<Brand>();
    private BrandBottomAdapter bottomAdapter = null;
    private int count;
    private final int delete = 3;
    private int isFirst = 1;

    private void fillDataBottom(final int page) {
        RequestParams params = new RequestParams();
        params.put("page", String.valueOf(page));
        params.put("pageSize", "10");
        // final ProgressHUD ProgressDialog = ProgressHUD.show(this, "正在加载...", true, true, null);
        AddClient.get(Address.SHOPBRAND, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                /*
                 * if (null != ProgressDialog && ProgressDialog.isShowing()) {
                 * ProgressDialog.dismiss(); }
                 */
                try {
                    ShopBrand shop = JSON.parseObject(content, ShopBrand.class);
                    if (shop.getStatus().equals("1")) {
                        onLoaded();
                        if (!shop.getMsg().equals("暂无数据！")) {
                            LinkedList<Brand> info = shop.getData().getInfo();
                            if (info.size() > 0) {
                                if (isFirst == 1) {
                                    info.removeFirst();
                                    info.removeFirst();
                                    info.removeFirst();
                                    brandsbottom.addAll(info);
                                    isFirst = 100;
                                } else {
                                    brandsbottom.addAll(info);
                                }
                                if (bottomAdapter == null) {
                                    /*
                                     * if(page==1){
                                     * 
                                     * brandsbottom.removeFirst(); brandsbottom.removeFirst(); }
                                     */
                                    bottomAdapter = new BrandBottomAdapter(brandsbottom);
                                    brand_list.getRefreshableView().setAdapter(bottomAdapter);
                                } else {
                                    bottomAdapter.notifyDataSetChanged();
                                }
                            }
                            count = Integer.parseInt(shop.data.count);
                            onLoaded();
                        } else {
                            onLoaded();
                            Toast.makeText(getApplicationContext(), "没有数据了", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
                    onLoaded();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFinish() {
                if (loading != null && loading.getVisibility() == View.VISIBLE) {
                    loading.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(Throwable error, String content) {
                /*
                 * if (null != ProgressDialog && ProgressDialog.isShowing()) {
                 * ProgressDialog.dismiss(); }
                 */
                onLoaded();
                Toast.makeText(getApplicationContext(), "获取信息失败", Toast.LENGTH_SHORT).show();
                super.onFailure(error, content);
            }
        });
    }

    private class BrandTopAdapter extends BaseAdapter {
        private final LinkedList<Brand> brandtop;

        public BrandTopAdapter(LinkedList<Brand> brandtop) {
            super();
            this.brandtop = brandtop;
        }

        @Override
        public int getCount() {
            return brandtop.size();
        }

        @Override
        public Object getItem(int position) {
            return brandtop.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolderTop holder;
            if (convertView == null) {
                holder = new ViewHolderTop();
                convertView = View.inflate(BrandActivity.this, R.layout.brand_top_item, null);
                holder.brand_top_pic = (ImageView) convertView.findViewById(R.id.brand_top_pic);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolderTop) convertView.getTag();
            }
            ImageLoader.getInstance().displayImage(brandtop.get(position).getBrand_logo(),
                    holder.brand_top_pic);
            return convertView;
        }
    }

    class ViewHolderTop {
        ImageView brand_top_pic;
    }

    private void initClick() {
        tittle_shop_cancel.setOnClickListener(this);
        tittle_shop_content.setText("品牌馆");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tittle_shop_cancel:
                finish();
                break;

            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (brandstop != null && brandstop.size() > 0) {
            brandstop.clear();
        }
        if (brandstop != null && brandsbottom.size() > 0) {
            brandsbottom.clear();
        }
        super.onDestroy();
    }

    private void onLoaded() {
        brand_list.onPullDownRefreshComplete();
        brand_list.onPullUpRefreshComplete();
    }

    private void setLastUpdateTime() {
        String text = CommonUtil.formatPullToRefreshDate();
        brand_list.setLastUpdatedLabel(text);
    }

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_brand;
    }
}
